package cn.edu.cxcyzx.util;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import cn.edu.cxcyzx.conf.Git;
import cn.edu.cxcyzx.entity.Gitee;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;



public class GiteeOauth {
	private String url=Git.gitee_token_url;
	private String grant_type="authorization_code";
	private String code="";
	private String client_id="";
	private String redirect_uri=Git.gitee_callBack_url;
	private String client_secret="";
	
	public GiteeOauth(String code,String client_id,String client_secret) {
		this.code=code;
		this.client_id=client_id;
		this.client_secret=client_secret;
		
	}
	
	public Gitee doPost() {
		Gitee gitee=null;
		HttpPost httpPost=new HttpPost(url);
		CloseableHttpClient client=HttpClients.createDefault();
		String respContent=null;
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("grant_type", grant_type);
		jsonObject.put("code", code);
		jsonObject.put("client_id", client_id);
		jsonObject.put("redirect_uri", redirect_uri);
		jsonObject.put("client_secret", client_secret);
		StringEntity entity=new StringEntity(jsonObject.toString(), "utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		//设置User-Agent,否则请求码403
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
		httpPost.setEntity(entity);
		System.out.println("into_______GiteeOauth");
		HttpResponse httpResponse = null;
		try {
			httpResponse = client.execute(httpPost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int resultCode=httpResponse.getStatusLine().getStatusCode();
		System.out.println("resultCode:"+resultCode);
		if(resultCode==200) {
			HttpEntity entity2=httpResponse.getEntity();
			try {
				gitee=JSON.parseObject(EntityUtils.toString(entity2, "utf-8"),Gitee.class);
				System.out.println("gitee:"+gitee.toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					client.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		return gitee;
	}

}
